package GUI;

import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.*;

import ExecuteEngine.*;
import Socket.Abort_Message;

public class QueryPanel extends JPanel {

	private static final long serialVersionUID = 4132315009401354318L;

	private ClientFrame frame;
	JTextArea queryArea;
	JButton execButton;

	public QueryPanel(ClientFrame frame) {
		this.frame = frame;
		setBorder(BorderFactory.createTitledBorder("Query"));
		
		initComponent();
		queryArea.addFocusListener(new FocusListener() {

			@Override
			public void focusGained(FocusEvent e) {
				queryArea.setText("");
			}

			@Override
			public void focusLost(FocusEvent e) {}
			
		});
	}
	private void initComponent() {
		execButton = new JButton("Execute");
		execButton.setBounds(350, 120, 80, 30);
		queryArea = new JTextArea("");
		JScrollPane jsp = new JScrollPane(queryArea);
		queryArea.setLineWrap(true);
		add(jsp);
		add(execButton, BorderLayout.EAST);
		execButton.setIcon(new ImageIcon("img/logo_1.png"));
		execButton.setOpaque(false);
		execButton.setPreferredSize(new Dimension(120,30));
		jsp.setPreferredSize(new Dimension(290, 130));
		jsp.setBounds(5, 5, 290, 160);
		execButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				String s = queryArea.getText().trim();
				if (s.equals("")) {
					frame.message.AddMessage("Warning: Query command line should not be blank.");
					return;
				}
            	int ret=-1;
            	try {
            		ret = frame.client.queryExec(queryArea.getText().trim());
            	} catch (Abort_Message m) {
            		frame.message.AddMessage("Warning: "+m.getMessage());
            		return;
            	}
        		frame.message.AddMessage("Success: SQL Line Execution Success");
            	if (ret == Operation.PROJECT || ret == Operation.SORT) {
            		frame.table.updateTable();
            	} else if (ret == Operation.SPECIALOP) {
            		frame.tree.updateTree();
            	}
            }
		});
	}
	
}
